import SelectWidget from '../../widgets/SelectWidget.js';

const TvaProductFormMixin = {
    /*
     * Mixin handling tva + product synchronization inside a form
     *
     * Expects the View to have :
     *
     * a model with tva_id and product_id attributes
     * an attribute all_product_options
     * an attribute product_options (current options)
     * an attributes tva_options
     *
     * a product_id region
     *
     */

    getDefaultTva() {
        let result = _.findWhere(this.tva_options, {
            default: true
        });
        if (!result) {
            result = this.tva_options[0];
        }
        return result;
    },
    getCurrentTvaId() {
        /*
        Return the tva id of the current model
        Can be overridden if needed
        */
        let tva_id;
        if (this.model.has('tva_id')) {
            tva_id = this.model.get('tva_id');
        } else if (!this.model.props || !('tva_id' in this.model.props)) {
            console.error("This model has no tva_id declared, did you forget to override the getCurrentTvaId method ?");
        }
        return tva_id;
    },
    getProductOptions(tva_options, product_options, tva_id) {
        /*
         *  Return an array on filtered products option depending on selected tva
         *  :params list tva_options:
         *  :params list product_options:
         *  :params int tva_id: optionnal tva id
         */
        if (!tva_id) {
            tva_id = this.getCurrentTvaId();
        }
        let options = [];

        if (tva_id) {
            options = _.filter(product_options, function (product) {
                return product.tva_id === parseInt(tva_id);
            });
        }
        return options;
    },
    refreshTvaProductSelect(event) {
        /**
         * Update and show the TVA products option select
         * :param obj event
         */
        this.product_options = this.getProductOptions(
            this.tva_options,
            this.all_product_options,
        );
        this.showChildView(
            'product_id',
            new SelectWidget({
                options: this.product_options,
                title: "Compte produit",
                value: this.model.get('product_id'),
                field_name: 'product_id',
                id_key: 'id',
                placeholder: 'Choisir un compte produit',
            })
        );
    },
}
export default TvaProductFormMixin;